package com.blog.kit;

import com.google.gson.Gson;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

/**
 * Created by ${wangjian} on 2017/11/15.
 */
public class JsonKit {

    private static Gson gson = new Gson();

    public static <T> T fromJson(String str, Class<T> clazz, Class... clazzs) {
        if (null != clazzs && clazzs.length > 0) {
            ParameterizedType objectType = type(clazz, clazzs);
            return gson.fromJson(str, objectType);
        } else {
            return gson.fromJson(str, clazz);
        }
    }

    public static String toJson(Object object) {
        return null == object ? null : gson.toJson(object);
    }

    private static ParameterizedType type(final Class raw, final Type... args) {
        return new ParameterizedType() {
            public Type getRawType() {
                return raw;
            }
            public Type[] getActualTypeArguments() {
                return args;
            }
            public Type getOwnerType() {
                return null;
            }
        };
    }
}
